import 'dart:io';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:url_launcher/url_launcher_string.dart';

import '../common/user_helper.dart';

class URLOpenUtils {
  /// 腾讯地图调用
  static Future<bool> openTencentMap(double longitude, double latitude,
      {String address, bool showErr: true}) async {
    String url =
        'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=FN4BZ-6E33P-LFTDB-VRZ4C-NTP3Z-RVFFK&debug=true&to=${address ?? ''}';
    if (Platform.isIOS) url = Uri.encodeFull(url);
    try {
      if (await canLaunch(url) != null) {
        await launch(url);
      }
    } on Exception catch (e) {
      if (showErr) showToastCommon('无法调起腾讯地图');
      return false;
    }
    return true;
  }

  /// 高德地图调用
  static Future<bool> openAmapNav(
    double longitude,
    double latitude, {
    String address,
    bool showErr = true,
  }) async {
    String url =
        '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2&poiname=${address ?? ''}';
    if (Platform.isIOS) url = Uri.encodeFull(url);
    try {
      if (await canLaunchUrlString(url)) {
        await launchUrlString(url);
        return true;
      } else {
        if (showErr) showToastCommon('未检测到高德地图APP 请安装高德地图APP使用此功能');
        return false;
      }
    } on Exception catch (e) {
      if (showErr) showToastCommon('无法调起高德地图');
      return false;
    }
  }

  static Future<bool> openAmap(
    double longitude,
    double latitude, {
    String address,
    String title,
    bool showErr = true,
  }) async {
    String url = "";
    if (Platform.isAndroid) {
      url =
          'androidamap://viewReGeo?sourceApplication=${title ?? ""}&lat=$latitude&lon=$longitude&dev=0';
    } else {
      url =
          "iosamap://viewMap?sourceApplication=${title ?? ""}&poiname=${title ?? ""}&lat=$latitude&lon=$longitude&dev=0";
    }
    if (Platform.isIOS) url = Uri.encodeFull(url);
    try {
      if (await canLaunchUrlString(url)) {
        await launchUrlString(url);
        return true;
      } else {
        url =
            "https://m.amap.com/navi/?dest=$longitude,$latitude&destName=${title ?? ""}&hideRouteIcon=1&key=4ade3d8f31d914903631dd001b1d1d16";
        if (UserHelper.getInstance.userLongitude != null) {
          String userLongitude =
              UserHelper.getInstance.userLongitude.toStringAsFixed(6);
          String userLatitude =
              UserHelper.getInstance.userLatitude.toStringAsFixed(6);
          url =
              "http://api.map.baidu.com/direction?region=中国&origin=latlng:$userLatitude,$userLongitude|name:当前位置&destination=latlng:$latitude,$longitude|name:${title ?? "终点"}&mode=driving&output=html&coord_type=gcj02&src=webapp.baidu.openAPIdemo";
          // url ="https://m.amap.com/navi/?start=$userLongitude,$userLatitude&dest=$longitude,$latitude&destName=${title ?? ""}&naviBy=car&key=4ade3d8f31d914903631dd001b1d1d16";
        }

        LogUtil.e("地图导航  $url");

        if (await canLaunchUrlString(url)) {
          await launchUrlString(url, mode: LaunchMode.externalApplication);
          return true;
        } else {
          if (showErr) showToastCommon('未检测到高德地图APP 请安装高德地图APP使用此功能');
        }
        return false;
      }
    } on Exception catch (e) {
      if (showErr) showToastCommon('无法调起高德地图');
      return false;
    }
  }

  /// 百度地图
  static Future<bool> openBaiduMap(
    double longitude,
    double latitude, {
    String address,
    bool showErr = true,
    String title,
  }) async {
    String url = "";
    if (Platform.isIOS) {
      url =
          "bdapp://map/geocoder?location=$latitude,$longitude&src=${title ?? ""}&coord_type=gcj02";
    } else {
      url =
          "baidumap://map/geocoder?location=$latitude,$longitude&coord_type=gcj02&src=${title ?? ""}";
    }
    try {
      if (await canLaunchUrlString(url)) {
        await launchUrlString(url);
        return true;
      } else {
        url =
            "http://api.map.baidu.com/geocoder?location=$latitude,$longitude&coord_type=gcj02&output=html&src=webapp.baidu.openAPIdemo";
        if (await canLaunchUrlString(url)) {
          await launchUrlString(url);
          ToastUtils.showToast("打开成功");
          return true;
        }
        if (showErr) showToastCommon('未检测到百度地图APP 请安装百度地图APP使用此功能');
        return false;
      }
    } on Exception catch (e) {
      if (showErr) showToastCommon('无法调起百度地图 ');
      return false;
    }
  }

  static Future<bool> openBaiduMapNav(
    double longitude,
    double latitude, {
    String address,
    bool showErr = true,
    String title,
  }) async {
    String url =
        'baidumap://map/direction?destination=name:${address ?? ''}|latlng:$latitude,$longitude&coord_type=bd09ll&mode=driving';
    if (Platform.isIOS) url = Uri.encodeFull(url);
    try {
      if (await canLaunchUrlString(url)) {
        await launchUrlString(url);
      }
    } on Exception catch (e) {
      if (showErr) showToastCommon('无法调起百度地图');
      return false;
    }
    return true;
  }

  /// 苹果地图
  static Future<bool> openAppleMap(longitude, latitude,
      {String address, bool showErr: true}) async {
    String url =
        'http://maps.apple.com/?daddr=$latitude,$longitude&address=$address';
    if (Platform.isIOS) url = Uri.encodeFull(url);
    try {
      if (await canLaunch(url) != null) {
        await launch(url);
      }
    } on Exception catch (e) {
      if (showErr) showToastCommon('无法调起高德地图');
      return false;
    }
    return true;
  }

  static Future<bool> openMap(longitude, latitude,
      {String address, bool showErr: false}) async {
    bool flag = true;
    if (!await openAmap(longitude, latitude,
        address: address, showErr: showErr)) {
      if (!await openBaiduMap(longitude, latitude,
          address: address, showErr: showErr)) {
        if (!await openTencentMap(longitude, latitude,
            address: address, showErr: showErr)) {
          // if (!await openAppleMap(longitude, latitude, address: address, showErr: showErr)) {
          flag = false;
          showToastCommon('无法调用地图应用，请安装高德，百度，腾讯任意一种地图应用');
          // }
        }
      }
    }
    return flag;
  }

  static showToastCommon(String message) {
    Get.defaultDialog(
        title: "提示",
        middleText: message,
        backgroundColor: Colors.white,
        titleStyle: const TextStyle(color: Colors.black),
        middleTextStyle: const TextStyle(color: Colors.red),
        textConfirm: "知道了",
        confirmTextColor: Colors.white,
        onConfirm: () {
          Get.back();
        },
        radius: 8);
  }
}
